<template>
<div>
<el-tabs value="base">
  <el-tab-pane label="基本信息" name="base">
  <el-form v-model="contract">
    <el-row>
      <el-col :span="8">
        <el-form-item label="采购组织" prop="purOrgId">
          <el-select v-model="contract.purOrgId" @change="changePurOrg" :disabled="contract.sourceType==1">
            <el-option v-for="item in purOrgOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="采购组" prop="purGroupId">
          <el-select v-model="contract.purGroupId">
            <el-option v-for="item in purGroupOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="说明附件">
          <input class="file" type="file"  @change="changeFile('noticeFile',$event)"/> 
          <el-button type="text" @click="downloadAtt(contract.noticeAttFileUrl,contract.noticeAttFileName)">{{contract.noticeAttFileName}}</el-button>
           <!-- <el-upload :action="uploadUrl" :file-list="noticeList" :data="uploadData" 
          :on-success="noticeUploadSc"
          :before-remove="noticeRm"
          >
            <el-button size="small" type="primary">点击上传</el-button> 
          </el-upload> -->
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8">
        <el-form-item label="合同模式">
          <el-radio-group v-model="contract.contractModel" @change="changeModel">
          <el-radio :label="0">标准</el-radio>
          <el-radio :label="1">非标准</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="允许超量">
          <el-radio-group v-model="contract.excessFlag">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="contract.contractModel==1">
        <el-form-item label="非标合同附件" prop="contractFileList">
          <!-- <el-upload :action="uploadUrl" :file-list="contractFileList" :data="uploadData" 
          :on-success="contractFileUploadSc"
          :before-remove="contractFileRm"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload> -->
          <input class="file" type="file"  @change="changeFile('contractFile',$event)"/> 
          <el-button type="text" @click="downloadAtt(contract.attFileUrl,contract.attFileName)">{{contract.attFileName}}</el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="8" v-if="contract.contractModel==1">
        <el-form-item label="公司">
          <el-select v-model="contract.companyId" placeholder="请输入关键字" filterable remote :loading="loading" :remote-method="companyQuery">
            <el-option v-for="item in companyOptionList" :key="item.value" :label="item.text" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="contract.contractModel==1">
        <el-form-item label="供应商">
          <el-select v-model="contract.vendorId" filterable remote  :loading="loading" :remote-method="vendorQuery" :disabled="contract.sourceType==1">
            <el-option v-for="item in vendorOptionList" :key="item.value" :label="item.text" :value="item.value"/>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" v-if="erpFlag">
        <el-form-item label="协议类型" prop="bsartDictItemId">
          <el-select v-model="contract.bsartDictItemId">
            <el-option v-for="item in purContractTypeList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-form-item label="合同公告">
          <UE v-model="contract.notice" :config="config" ref="ue"></UE>
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
  </el-tab-pane>
  <el-tab-pane label="模板选择" name="template" v-if="contract.contractModel==0">
    <table-ext :searchForm="template.searchForm" :columns="template.columns" :config="template.config" ref="tableExt">
    </table-ext>
  </el-tab-pane>
</el-tabs>
<div style="margin-top: 10px;text-align:right">
  <el-button type="primary" @click="create()">保存</el-button>
  <!-- <el-button type="danger" @click="resetForm()">重置</el-button> -->
</div>
</div>
</template>
<script>
  import TableExt from '@/components/common/table-ext/table-ext.vue';
  import TableIcon from '@/components/common/table-ext/table-icon';
  import UE from '@/components/common/ue/ue.vue';
   export default {
    props: ['contract','purContractTypeList'],
    // 引入自定义表格组件
    components:{
      'table-ext': TableExt,
      UE
    },
    data() {
      return {
        loading: false,
        companyOptionList: [],
        vendorOptionList:[],
        purOrgOptions: [],
        purGroupOptions: [],
        uploadUrl: this.lib.config.host.system + '/common/fileupload/upload',
        uploadData: {busAction:'upload',tableName:'contract'},
        noticeList: [],
        contractFileList: [],
        defaultMsg: '',
        noticeFile: '',
        contractFile: '',
        config: {
            // initialFrameWidth: '90%',
            // initialFrameHeight: '90%',
            enableAutoSave: false,
            zIndex:9999
        },
        // formRules: {
        //   purOrgId: [
        //     { required: true, message: '请选择采购组织', trigger: 'change' }
        //   ],
        //   purGroupId: [
        //     { required: true, message: '请选择采购组', trigger: 'change' }
        //   ],
        //   bsartDictItemId: [
        //     {required: true,message: '请选择采购协议',trgger: 'change'}
        //   ],
        //   contractFileList: [
        //     {required: true,message: '请上传合同',trgger: 'change'}
        //   ]

        // },
        
        template: {
          config:{ // 页面共通配置
            title: '合同模板', //页面标题
            isPage: true, //是否分页
            isNo: false, //是否显示序号
            selection: true,//显示checkbox
            checkedIdArray: [],
            crudMapping:{ // CRUD方法
              query:{
                url: this.lib.config.host.contract + '/contractmgt/template/query',
                data: {disableFlag:0}
              }
            }
          },
          // 查询表单配置
          searchForm:[{
            label: '模板名称', 
            key: 'name', 
            type: 'input' 
          }
          ],
          // 表格列定义
          columns:[{
            label: 'id',
            key: 'id',
            hidden: true
          },{
            label: '编码',
            key: 'code',
            render:(h,ctx)=>{
              let _this = this;
              return h('el-button',{
                props: {
                  type: 'text'
                },
                on: {
                  click(){

                  }
                }
              },ctx.row.code);
            }
          },{
            label: '名称',
            key: 'name'
          },{
            label: '禁用标记',
            key: 'disableFlag',
            align: 'center',
            render:(createElement, params)=>{ //动态渲染, 字典表示例
              return createElement(TableIcon,{props:{
                  flag: params.row.disableFlag,
                  titles: [{status:0,title:'启用'},{status:1,title:'禁用'}]
              }});
            }
          },{
            label: '超量标记',
            key: 'excessFlag',
            align: 'center',
            render:(createElement, params)=>{ //动态渲染, 字典表示例
              return createElement(TableIcon,{props:{
                  flag: params.row.excessFlag,
                  titles: [{status:0,title:'否'},{status:1,title:'是'}]
              }});
            }
          }
        ]
      
        }
      }
    },
    mounted(){
      this.init();
    },
    computed: {
      erpFlag(){
        return true;
        if(this.contract==null || this.contract.company==null){
          return false;
        }
        return this.contract.company.erpFlag==1?true:false;
      }
    },
    watch: {
     contract(val){
       this.init();
     }
    },
    methods: {
      init(){
        let _this = this;
        this.getPurOrgSelect(this.getCurrUserId()).then(data=>{
          _this.purOrgOptions = data;
        });
        if(this.contract.id){
          if(this.contract.contractModel==0){
            this.$refs.tableExt.clearSelection();
            this.$refs.tableExt.toggleRowSelection(this.contract.contractTemplateId);
          }
        }
        if(this.contract.purOrgId){
          this.changePurOrg(this.contract.purOrgId);
        }
        if(this.contract.sourceType || this.contract.id){
          if(this.contract.companyId){
          this.companyOptionList.push({value:this.contract.companyId,text:this.contract.companyName});
          }
          if(this.contract.vendorId){
          this.vendorOptionList.push({value:this.contract.vendorId,text:this.contract.vendorName});
          }
        }
      },
      changePurOrg(value){
        let _this = this;
        this.getPurGroupSelect(value).then(data=>{
          _this.purGroupOptions = data;
        });
      },
      changeModel(value){
        this.contractModel = value;
      },
      noticeUploadSc(res){
        this.contract.noticeAttFileUrl = res.url;
        this.contract.noticeAttFileName = res.fileName;
        this.contract.noticeAttId = res.id;
      },
      contractFileUploadSc(res){
        this.contract.attFileName = res.fileName;
        this.contract.attFileUrl = res.url;
        this.contract.attFileId = res.id;
      },
      noticeRm(file,fileList){
        if(this.contract.noticeAttId==''){
          return true;
        }
        this.deleteFile(this.contract.noticeAttId).then(result=>{
            if(result.success){
            this.contract.noticeAttFileUrl = '';
            this.contract.noticeAttFileName = '';
            this.contract.noticeAttId = '';
            this.noticeList = [];
            }else{
            this.showMsg('error',result.message);
            }
        });
        return false;
      },
      changeFile(key,event){
        this[key] = event.target.files[0];  
      },
      contractFileRm(file,fileList){
        if(this.contract.attFileId==''){
          return true;
        }
        this.deleteFile(this.contract.noticeAttId).then(result=>{
            if(result.success){
            this.contract.attFileName = '';
            this.contract.attFileUrl = '';
            this.contract.attFileId = '';
            this.contractFileList = [];
            }else{
            this.showMsg('error',result.message);
            }
        });
        return false;
      },
      downloadAtt(attFileUrl,attFileName){
        this.downloadFile(attFileUrl,attFileName);
      },
      create() {
        if(!this.contract.purOrgId){
          this.showMsg('warning','请选择采购组织');
          return;
        }
        if(!this.contract.purGroupId){
          this.showMsg('warning','请选择采购组');
          return;
        }
        // if(this.contract.contractModel==1 && !this.contract.attFileUrl){
        //   this.showMsg('warning','非标合同必须上传合同附件');
        //   return;
        // }
        if(this.erpFlag && !this.contract.bsartDictItemId){
          this.showMsg('warning','请选择采购协议');
          return;
        }
   
        
        if(this.contract.contractModel == 0){
          let templateList = this.$refs.tableExt.multipleSelection;
          if(templateList.length==0){
            this.showMsg('warning','没有选择模板');
            return;
          }
          if(templateList.length>1){
            this.showMsg('warning','只能选择一个模板');
            return;
          }
          let template = templateList[0];
          this.contract.contractTemplateId = template.id;
        }else{
          if(!this.contract.id && !this.contractFile){
            this.showMsg('warning','非标合同必须上传合同附件');
            return;
          }
          if(!this.contract.vendorId){
            this.showMsg('warning','非标合同必须选择供应商');
            return;
          }
          if(!this.contract.companyId){
            this.showMsg('warning','非标合同必须选择公司');
            return;
          }
        }
        debugger;
        let noticeContent = this.$refs.ue.getUEContent();
        this.contract.notice = noticeContent;

        let formData = new FormData();  
        for(let key in this.contract){
          if(typeof this.contract[key] == 'string' ||  typeof this.contract[key]=='number'){
            formData.append(key,this.contract[key]);
          }
        }
        formData.append('contractFile',this.contractFile);
        formData.append('noticeFile',this.noticeFile);
        let config = {  
          headers: {  
            'Content-Type': 'multipart/form-data'  
          }  
        }  
        let url = '/contractmgt/contract/add';
        if(this.contract.id){
          url = '/contractmgt/contract/update';
        }

        this.axios.post(this.lib.config.host.contract+url, formData, config).then(res=>{
           let result = res.data;
           if(result.success){
             this.$emit('createSuc',result.resultMap.contractId,this.contract.contractModel);
           }else{
             this.showMsg('error',result.message);
           }
        })  
      } ,
      companyQuery(param){
        if (param !== '') {
          this.loading = true;
          this.axios.post(this.lib.config.host.masterData+'system/cmpMgt/company/selectNode/'+param,{}).
          then(res=>{
            var result = res.data;
            this.companyOptionList = result;
            this.loading = false;
          });
        } else {
          this.companyOptionList = [];
        }
      } ,
      vendorQuery(param){
        if (param !== '') {
          this.loading = true;
          this.axios.post(this.lib.config.host.masterData+'/system/orgmgt/organization/selectNode/'+param,{}).
          then(res=>{
            var result = res.data;
            this.vendorOptionList = result;
            this.loading = false;
          });
        } else {
          this.vendorOptionList = [];
        }
      } 

      // ,
      // resetForm(formName) {
         
      // }
    }
   }
</script>
<style>
</style>
